import React, {PropsWithChildren, useCallback, useEffect, useMemo, useState} from 'react'
import {
    Button,
    Card,
    Collapse, DatePicker,
    Descriptions,
    Divider,
    Drawer, DrawerProps,
    Empty,
    Form,
    List, Modal,
    Pagination, Skeleton,
    Space, Table,
    Typography
} from "antd";
import {
    ConfigureMarketSettlementPlanResponse,
    getMarketSettlementPlan
} from "../../apis/MarketSettlementPlanApi";
import {Pageable} from "../../utils/Page";
import dayjs from "dayjs";
import {
    getExistedYearMonthOfMarketSaleDocumentsByMarketId
} from "../../apis/MarketSaleDocumentApi";
import LoadableButton from "../LoadableButton";
import ArrayUtils from "@zxy-cn/array-utils";
import {
    previewMarketSettlementPlanRuleDetail
} from "../../apis/MarketSettlementPlanDetailPreviewApi";
import {
    findMonthlyMarketSettlementSummary,
    findMonthlySettlementDocuments,
    generateMarketSettlementResult,
    getCopiedMarketSettlementPlanResultPlan,
    MarketSettlementPlanResultPlanResponse,
    MarketSettlementPlanResultResponse, MarketSettlementPlanResultSummary,
    previewMonthlySettlementDocuments,
    PreviewMonthlySettlementResultsResponse,
    PreviewMonthlySettlementResultsRuleFeeResponse,
} from "../../apis/MarketSettlementPlanResultApi";
import EditMarketSettlementPlanDrawer, {MarketSettlementPlanRow} from '../EditMarketSettlementPlanDrawer';
import {
    MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse
} from '../../apis/MarketShoppingGuideSalaryPlanDetailPreviewApi';
import {GoodsMatcherResultDrawer} from "../GoodsMatcherRuleFormItems";

export interface MarketSettlementTabPanelProps extends PropsWithChildren {
    id: number
}

const MarketSettlementTabPanel: React.FC<MarketSettlementTabPanelProps> = ({id}) => {
    const [configuration, setConfiguration] = useState<ConfigureMarketSettlementPlanResponse>()
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        setLoading(true)
        getMarketSettlementPlan(id).then(response => {
            setConfiguration(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id]);
    const [openConfigureMarketSettlementPlanDrawer, setOpenConfigureMarketSettlementPlanDrawer] = useState(false)
    const [loadingSalaryDocument, setLoadingSalaryDocument] = useState(false)

    const [pageable, setPageable] = useState(new Pageable())
    const [settlementDocuments, setSettlementDocuments] = useState<MarketSettlementPlanResultSummary[]>([])


    const [totalElements, setTotalElements] = useState(0)

    const [openGenerateSalaryDocumentDrawer, setOpenGenerateSalaryDocumentDrawer] = useState(false)
    let querySalaryDocuments = useCallback(() => {
        setLoadingSalaryDocument(true)
        findMonthlyMarketSettlementSummary(id, pageable).then(response => {
            setSettlementDocuments(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoadingSalaryDocument(false)
        })
    }, [id, ...pageable.toDependencyList()]);
    useEffect(() => {
        querySalaryDocuments()
    }, [querySalaryDocuments]);

    return <>
        <Space direction={"vertical"} style={{width: "100%"}}>
            <Card loading={loading} title={"方案"} extra={<Space>
                <Button onClick={() => {
                    setOpenConfigureMarketSettlementPlanDrawer(true)
                }}>配置</Button>
            </Space>}>

                {configuration ? <>
                    <Space direction={"vertical"}>
                        {configuration.rules.map(rule => {
                            return <MarketSettlementPlanRow value={rule}/>
                        })}
                    </Space>
                </> : "未配置"}
            </Card>
            <Card loading={loadingSalaryDocument} title={"结算单"}
                  extra={<>{<Button disabled={!configuration} onClick={() => {
                      setOpenGenerateSalaryDocumentDrawer(true)
                  }}>根据配置生成</Button>}</>}>
                {!loadingSalaryDocument && totalElements === 0 ? <Empty/> : <>

                    <Collapse
                        items={(settlementDocuments.map(document => ({
                            label: <div style={{display: "flex", justifyContent: "space-between"}}>
                                <div>{`${document.year}年${document.month}月`}</div>
                                <div>总计<Typography.Text strong>{document.totalFee}</Typography.Text></div>
                            </div>,
                            children: <MonthlyMarketSettlementCollapseContent marketId={id} year={document.year}
                                                                              month={document.month}/>
                        })))}/>
                    <div style={{display: "flex", justifyContent: "center", marginTop: 24}}>
                        <Pagination style={{justifyContent: "center"}} current={pageable.page} pageSize={pageable.size}
                                    total={totalElements}
                                    onChange={(page, size) => {
                                        setPageable(new Pageable(page, size))
                                    }}/>
                    </div>
                </>}

            </Card>
        </Space>
        <EditMarketSettlementPlanDrawer initialValue={configuration}
                                        open={openConfigureMarketSettlementPlanDrawer}
                                        onClose={function (): void {
                                            setOpenConfigureMarketSettlementPlanDrawer(false)
                                        }} marketId={id}
                                        onCompleted={function (value: ConfigureMarketSettlementPlanResponse): void {
                                            setConfiguration(value)
                                            setOpenConfigureMarketSettlementPlanDrawer(false)
                                        }}/>
        {
            <GenerateMarketGuideSalaryDocumentDrawer open={openGenerateSalaryDocumentDrawer}
                                                     id={id}
                                                     onCompleted={() => {
                                                         setOpenGenerateSalaryDocumentDrawer(false)
                                                         querySalaryDocuments()
                                                     }}
                                                     onClose={() => setOpenGenerateSalaryDocumentDrawer(false)}/>}
    </>
}

export default MarketSettlementTabPanel


export interface GenerateMarketGuideSalaryDocumentDrawerProps extends PropsWithChildren {
    id: number
    open: boolean
    onClose: () => void
    onCompleted: () => void
}

/**
 * 用于生成结算单
 *
 * 获取所有销量记录存在的月份，用于选择月份，选择月份后，显示结算单的预览，若点击生成，则在服务器生成此结算单。
 * @param id 卖场id
 */
const GenerateMarketGuideSalaryDocumentDrawer: React.FC<GenerateMarketGuideSalaryDocumentDrawerProps> = ({
                                                                                                             id,
                                                                                                             open,
                                                                                                             onClose,
                                                                                                             onCompleted
                                                                                                         }) => {
    const [existedYearMonth, setExistedYearMonth] = useState<string[]>([])
    useEffect(() => {
        if (open)
            getExistedYearMonthOfMarketSaleDocumentsByMarketId(id).then(response => {
                setExistedYearMonth(response.data)
            })
    }, [id, open]);

    const [year, setYear] = useState(new Date().getFullYear())
    const [month, setMonth] = useState(new Date().getMonth())

    const existedYearMonthDayjsArray = useMemo(() => {
        return existedYearMonth.map(it => dayjs(it))
    }, [existedYearMonth]);

    const monthHasData = useMemo(() => {
        return existedYearMonthDayjsArray.some(it => it.year() === year && it.month() === month - 1)
    }, [year, month, existedYearMonthDayjsArray]);
    useEffect(() => {
        if (open && monthHasData) {
            previewMonthlySettlementDocuments(id, year, month).then(response => {
                setPreviewData(response.data)
            })
        }
    }, [year, month, id, open, monthHasData]);

    const [previewData, setPreviewData] = useState<PreviewMonthlySettlementResultsResponse>()
    const [modal, contextHolder] = Modal.useModal();

    const [previewRuleId, setPreviewDetailRuleId] = useState<number>()
    return <>
        {contextHolder}
        <MarketSettlementRuleDetailPreviewDrawer open={!!previewRuleId} ruleId={previewRuleId} year={year} month={month}
                                                 onClose={() => {
                                           setPreviewDetailRuleId(undefined)
                                       }}/>
        <Drawer title={"生成结算单"} open={open} onClose={onClose} width={document.body.clientWidth * 0.618}>
            <Form>
                <Form.Item label={`选择月份`} required>
                    <DatePicker.MonthPicker
                        disabledDate={d => !existedYearMonthDayjsArray.some(i => d.year() === i.year() && d.month() === i.month())}
                        value={dayjs().year(year).month(month - 1)} onChange={value => {
                        setYear(value.year())
                        setMonth(value.month() + 1)
                    }}/>
                </Form.Item>
            </Form>
            {!!previewData && <>{/*    显示工资方案的统计数据,全部规则的,总工资,总销售,各个方案明细下的总销售,总工资*/}
                <Descriptions title={"结算单生成预览"} extra={<LoadableButton type={"primary"} onClick={async () => {
                    const confirmed = await modal.confirm({
                        title: "生成结算单将会删除旧的结算单（如果有），是否继续？",
                    })
                    if (confirmed) {
                        await generateMarketSettlementResult(id, year, month)
                        onCompleted()
                    }
                }}>生成</LoadableButton>}>
                    <Descriptions.Item label={"总销售额"}>{previewData.totalSale}</Descriptions.Item>
                    <Descriptions.Item label={"总费用"}>{previewData.totalFee}</Descriptions.Item>
                </Descriptions>
                <Divider/>
                <Table<PreviewMonthlySettlementResultsRuleFeeResponse> pagination={{position: ["none"]}} columns={
                    [
                        {title: "规则名称", dataIndex: "name", key: "name"},
                        {title: "产生费用", dataIndex: "salary", key: "salary"},
                        {title: "说明", dataIndex: "note", key: "note"},
                        {
                            title: "",
                            dataIndex: "actions",
                            render: (value, record, index) => {
                                return <>
                                    <Button type={"link"} onClick={() => {
                                        setPreviewDetailRuleId(record.id)
                                    }}>查看明细</Button>
                                </>
                            }
                        }
                    ]
                } dataSource={previewData.ruleFeeList}></Table>
            </>
            }

        </Drawer>
    </>
}

interface MonthlyMarketSalaryCollapseContentProps {
    marketId: number
    year: number
    month: number
}

const MonthlyMarketSettlementCollapseContent: React.FC<MonthlyMarketSalaryCollapseContentProps> = (props) => {
    const [data, setData] = useState<MarketSettlementPlanResultResponse>()
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        setLoading(true)
        findMonthlySettlementDocuments(props.marketId, props.year, props.month).then(response => {
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, []);
    return <>
        <Collapse items={[{
            key: 1,
            label: "方案",
            children: <MarketSettlementPlanResultCopiedPlanCollapseContent marketId={props.marketId} year={props.year}
                                                                           month={props.month}/>
        }]}/>
        <Divider/>

        {data ? <>
            <Descriptions>
                <Descriptions.Item label={"总销量"}>{data.totalSale}</Descriptions.Item>
                <Descriptions.Item label={"总费用"}>{ArrayUtils.sum(data.feeList, it => it.fee)}</Descriptions.Item>
                <Descriptions.Item
                    label={"结算金额"}>{data.totalSale - ArrayUtils.sum(data.feeList, it => it.fee)}</Descriptions.Item>
            </Descriptions>
            <Table<PreviewMonthlySettlementResultsRuleFeeResponse>
                pagination={{position: ["none"]}}
                dataSource={data.feeList}
                rowKey={"id"}
                columns={[{
                    title: "结算项",
                    dataIndex: "name"
                },
                    {
                        title: "费用",
                        dataIndex: "fee"
                    },
                    {
                        title: "备注",
                        dataIndex: "note"
                    }]}/>
        </> : <Space direction={"vertical"}>
            <Space>
                <Skeleton.Button active={loading}/>
                <Skeleton.Button active={loading}/>
                <Skeleton.Button active={loading}/>
                <Skeleton.Button active={loading}/>
            </Space>
            <Skeleton.Node active={loading} style={{width:200,height:120}}/>
        </Space>}

    </>
}

export interface SalaryRuleDetailPreviewDrawerProps extends DrawerProps {
    ruleId?: number
    year: number
    month: number
}

/**
 * TODO
 */
const MarketSettlementRuleDetailPreviewDrawer: React.FC<SalaryRuleDetailPreviewDrawerProps> = (props) => {
    const [data, setData] = useState<MarketShoppingGuideSalaryPlanRuleDetailPreviewResponse[]>([])
    useEffect(() => {
        if (props.ruleId)
            previewMarketSettlementPlanRuleDetail(props.ruleId, props.year, props.month).then(response => {
                setData(response.data)
            })
        else {
            setData([])
        }
    }, [props.ruleId, props.year, props.month]);
    return <>
        <GoodsMatcherResultDrawer data={data} {...props} width={document.body.clientWidth * 0.618}
                                  title={"结算单明细预览"}/>
    </>
}

export interface MarketSettlementPlanResultCopiedPlanCollapseContentProps {
    marketId: number
    year: number
    month: number
}

export const MarketSettlementPlanResultCopiedPlanCollapseContent: React.FC<MarketSettlementPlanResultCopiedPlanCollapseContentProps> = (props) => {
    const [data, setData] = useState<MarketSettlementPlanResultPlanResponse>()
    useEffect(() => {
        getCopiedMarketSettlementPlanResultPlan(props.marketId, props.year, props.month).then(response => {
            setData(response.data)
        })
    }, [props.year, props.month, props.marketId]);
    return <>
        {data?.rules?.map((rule, index) => {
            return <MarketSettlementPlanRow value={{...rule, id: index}}/>
        })}
    </>
}